package com.weiyi.weiman.interceptor;

import com.weiyi.weiman.utils.RedisUtils;
import com.weiyi.weiman.utils.IPUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhang
 * @Date 2021/5/1 下午11:48
 * @Description 小程序拦截器，只接受小程序发送的请求
 * @Version 1.0
 **/
@Slf4j
public class AppletInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Value("${weiman.ip-black-pre}")
    private String IP_BLACK_PRE;

    @Value("${weiman.referer}")
    private String REFERER;

    /**
     * controller方法调用前调用
     * 如果未登录则跳转登录页
     *
     * @return 往下执行则返回true，否则返回false
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //拦截非小程序发送的请求
        String ipAddr = IPUtils.getIpAddr(request);
//        if (!REFERER.equals(request.getHeader("Referer"))) {
//            log.info("请求ip:" + ipAddr + ",请求路径" + request.getRequestURI() + "  不是小程序请求，进行拦截");
//            redisUtils.setIfAbsent(IP_BLACK_PRE + ipAddr, "0");
//            redisUtils.incrBy(IP_BLACK_PRE + ipAddr, 1);
//            redisUtils.setExpire(IP_BLACK_PRE + ipAddr, 12, TimeUnit.HOURS);
//            return false;
//        }
        log.info("请求ip:" + ipAddr + ",请求路径" + request.getRequestURI() + "  放行");
        return true;
    }

    /**
     * controller方法调用后视图渲染前执行。
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    /**
     * controller方法调用且视图渲染完成后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
